import 'package:flutter/material.dart';
import 'package:flutter_screenutil/flutter_screenutil.dart';
import 'package:ayj_flutter_chat_app/common/widgets/widget_extennsion.dart';
import 'package:photo_manager/photo_manager.dart';

import '../../../generated/r_images.dart';
import '../../widgets/base_appbar.dart';
import '../../configs/colors.dart';
import '../../configs/dimens.dart';
import '../../configs/styles.dart';
import '../../widgets/app_image.dart';
import '../refresh/refresh.dart';
import 'asset_controller.dart';
import 'asset_tool.dart';
import 'package:photo_manager_image_provider/photo_manager_image_provider.dart';

class VolvoAssetPage extends StatefulWidget {
  static Future open(BuildContext context) {
    return Navigator.push(context,
        MaterialPageRoute(builder: (context) => VolvoAssetPage()),);
  }

  final LocalAssetType type;
  final int maxAssetCount;
  final int maxVideoLength;
  final ValueChanged<List<AssetEntity>>? selectedCallback;

  const VolvoAssetPage({
    super.key,
    this.type = LocalAssetType.image,
    this.maxAssetCount = 1,
    this.maxVideoLength = 15,
    this.selectedCallback,
  });

  @override
  State<VolvoAssetPage> createState() => _VolvoAssetPageState();
}

class _VolvoAssetPageState extends State<VolvoAssetPage> {
  late VolvoAssetController _assetController;

  @override
  void initState() {
    super.initState();
    _assetController = VolvoAssetController(
      type: widget.type,
      maxAssetCount: widget.maxAssetCount,
      maxVideoLength: widget.maxVideoLength,
      callback: widget.selectedCallback,
    );
  }

  @override
  void dispose() {
    _assetController.dispose();
    super.dispose();
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: BaseAppBar(
        // titleWidget: _buildTitle(),
         _assetController.currentPathName,
        rightWidgets: [
          Center(child:  _buildComplete(),),
        ],
      ),
      body: _buildContent(),
    );
  }

  /// 自定义Title
  // Widget _buildTitle() {
  //   return AnimatedBuilder(
  //     animation: _assetController,
  //     builder: (BuildContext context, Widget? child) {
  //       return _assetController.currentPathName.isEmpty
  //           ? const SizedBox()
  //           : GestureDetector(
  //               behavior: HitTestBehavior.opaque,
  //               child: Row(
  //                 crossAxisAlignment: CrossAxisAlignment.center,
  //                 mainAxisSize: MainAxisSize.min,
  //                 children: [
  //                   Text(
  //                     _assetController.currentPathName,
  //                     style: TextStyle(
  //                       fontSize: 16,
  //                       fontWeight: FontWeight.w400,
  //                       color: AppTheme.themeColor,
  //                     ),
  //                   ),
  //                   // AssetUtil.svgImage(
  //                   //   "packages/volvo_ui/assets/svg/photo/down_arrow",
  //                   //   // color: Colors.red,
  //                   //   size: Size(16, 16),
  //                   // ),
  //                 ],
  //               ),
  //               onTap: () {
  //                 _assetController.switchingPath();
  //               },
  //             );
  //     },
  //   );
  // }

  /// 完成
  Widget _buildComplete() {
    return AnimatedBuilder(
      animation: _assetController,
      builder: (BuildContext context, Widget? child) {
        return _assetController.selectedAssets.isNotEmpty
            ? GestureDetector(
          behavior: HitTestBehavior.opaque,
          child: Text(
            "完成(${_assetController.selectedAssets.length}/${widget.maxAssetCount})",
            style: KStyles.commonFontWeightTextStyle( Colors.white, 12),
          ).addContainer(
              padding: EdgeInsets.all(8.r),
              margin: EdgeInsets.only(right: 15.w),
              decoration: BoxDecoration(
                color: KColors.kThemeColor,
                borderRadius: BorderRadius.circular(10.r),
              ),
          ),
          onTap: () {
            _assetController.resultBack(context);
          },
        )
            : const SizedBox();
      },
    );
  }

  /// 路径Widget
  Widget _buildPathWidget() {
    return Positioned(
      top: 0,
      left: 0,
      right: 0,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: AnimatedBuilder(
          animation: _assetController,
          builder: (BuildContext context, Widget? child) {
            return AnimatedContainer(
              // color: _assetController.isSwitchingPath
              //     ? VolvoColors.foregroundPrimary.color
              //     : Colors.transparent,
                duration: const Duration(milliseconds: 150),
                height: _assetController.isSwitchingPath ? null : 0,
                child: _assetController.paths.isNotEmpty
                    ? AnimatedAlign(
                  alignment: Alignment.topCenter,
                  duration: const Duration(milliseconds: 150),
                  child: AnimatedOpacity(
                    opacity: _assetController.isSwitchingPath ? 1 : 0,
                    duration: const Duration(milliseconds: 150),
                    child: Container(
                      decoration: BoxDecoration(
                        color: KColors.kThemeColor,
                        borderRadius: BorderRadius.only(
                          bottomLeft:
                          Radius.circular(8.r),
                          bottomRight:
                          Radius.circular(8.r),
                        ),
                      ),
                      child: ListView.builder(
                        shrinkWrap: true,
                        padding: EdgeInsets.zero,
                        itemCount: _assetController.paths.length,
                        itemBuilder: (BuildContext context, int index) {
                          return _buildPathItem(index);
                        },
                      ),
                    ),
                  ),
                )
                    : const SizedBox());
          },
        ),
        onTap: () {
          _assetController.switchingPath();
        },
      ),
    );
  }

  Widget _buildPathItem(int index) {
    AssetPathModel pathModel = _assetController.paths[index];
    return GestureDetector(
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        height: 56,
        child: Row(
          children: [
            Container(
              width: 56,
              height: 56,
              padding: const EdgeInsets.all(2),
              child: AssetEntityImage(
                pathModel.assetEntity,
                isOriginal: false,
                fit: BoxFit.cover,
                thumbnailSize:
                ThumbnailSize.square(150.toInt()),
              ),
            ),
            Expanded(
              child: Padding(
                padding: const EdgeInsets.only(left: 8),
                child: Column(
                  children: [
                    Expanded(
                      child: Row(
                        children: [
                          Text(
                            pathModel.pathEntity.name,
                            style: KStyles.commonFontWeightTextStyle(
                              Colors.white,
                               16,
                            ),
                          ),
                          Padding(
                            padding: const EdgeInsets.only(left: 4),
                            child: Text(
                              "(${pathModel.assetCount})",
                              style: KStyles.commonFontWeightTextStyle(Colors.grey,
                                 14,
                              ),
                            ),
                          ),
                        ],
                      ),
                    ),
                    Container(
                      width: double.infinity,
                      height: 0.5,
                      color: Colors.grey,
                    )
                  ],
                ),
              ),
            ),
            if (pathModel.isSelected)
              Padding(
                  padding: const EdgeInsets.only(right: 8),
                  child:  AppImage.assets(AppR.update_success,
                    width: 24.r,
                    height: 24.r,
                  )

              ),
          ],
        ),
      ),
      onTap: () {
        _assetController.selectedPath(pathModel);
      },
    );
  }

  /// Refresh
  Widget _buildRefresh() {
    Size size = MediaQuery.of(context).size;
    return Refresh(
      controller: _assetController.refreshController,
      enablePullDown: false,
      enablePullUp: true,
      // footer: _buildFooter(),
      onRefresh: () async {
        _assetController.onRefresh();
      },
      onLoading: () async {
        _assetController.onLoading();
      },
      child: _buildGridView(),
    );
  }

  /// 自定义Footer
  // Widget _buildFooter() {
    // return ClassicFooter(
    //   textStyle: TextStyle(
    //     fontSize: 16,
    //     fontWeight: FontWeight.w400,
    //     color: AppTheme.primaryColor,
    //   ),
    //   idleText: "",
    //   canLoadingText: "",
    //   loadingText: "",
    //   noDataText: "",
    //   idleIcon: const SizedBox(),
    //   canLoadingIcon: const SizedBox(),
    //   loadingIcon: const SizedBox(),
    // );
  // }

  /// 内容
  Widget _buildContent() {
    return AnimatedBuilder(
      animation: _assetController,
      builder: (BuildContext context, Widget? child) {
        return Stack(
          fit: StackFit.expand,
          children: [
            _buildRefresh(),
            if (_assetController.isSwitchingPath) _buildPathWidget(),
          ],
        );
      },
    );
  }

  /// 资源Grid
  Widget _buildGridView() {
    return GridView.builder(
      key: ValueKey(_assetController.currentPathName),
      shrinkWrap: true,
      controller: ScrollController(initialScrollOffset: 0),
      // primary: true,
      physics: const AlwaysScrollableScrollPhysics(),
      padding: EdgeInsets.zero,
      gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
        crossAxisCount: 4,
        mainAxisSpacing: 2.r,
        crossAxisSpacing: 2.r,
        childAspectRatio: 1.r,
      ),
      itemCount: _assetController.dataList.length,
      itemBuilder: (context, index) {
        return _buildItem(index);
      },
    );
  }

  /// 图片Item
  Widget _buildItem(int index) {
    AssetModel model = _assetController.dataList[index];
    return RepaintBoundary(
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: Stack(
          fit: StackFit.expand,
          children: [
            _buildImage(model),
            _buildState(model),
            _buildVideoDuration(model),
          ],
        ),
        onTap: () {
          _assetController.preview(context, index);
        },
      ),
    );
  }

  /// 资源图片
  Widget _buildImage(AssetModel model) {
    return AssetEntityImage(
      model.assetEntity,
      isOriginal: false,
      fit: BoxFit.cover,
      thumbnailSize: ThumbnailSize.square(150.toInt()),
    );
  }

  /// 选择状态
  Widget _buildState(AssetModel model) {
    bool isSelected = model.isSelected;
    int index = _assetController.selectedAssets.indexOf(model) +
        1.toInt();
    return widget.maxAssetCount > 0
        ? Positioned(
      top: 0,
      right: 0,
      child: GestureDetector(
        behavior: HitTestBehavior.opaque,
        child: SizedBox(
          width: 44,
          height: 44,
          child: Align(
            alignment: Alignment.topRight,
            child: AnimatedContainer(
              width: 24,
              height: 24,
              margin: const EdgeInsets.only(
                  top: 5,
                  right: 5),
              duration: Duration(
                  milliseconds: 100.toInt()),
              decoration: BoxDecoration(
                color: isSelected
                    ? KColors.kThemeColor
                    : Colors.grey,
                border: Border.all(
                    color: isSelected
                        ? KColors.kThemeColor
                        : Colors.white,
                    width: 1),
                shape: BoxShape.circle,
              ),
              alignment: Alignment.center,
              child: isSelected
                  ? Text(
                "$index",
                style: KStyles.commonFontWeightTextStyle(
                    KColors.kThemeColor,14
                ),
              )
                  : null,
            ),
          ),
        ),
        onTap: () {
          _assetController.clickAsset(context, selectModel: model);
        },
      ),
    )
        : const SizedBox();
  }

  /// 视频时间
  Widget _buildVideoDuration(AssetModel model) {
    int duration = model.assetEntity.duration;
    String time = "";
    int rule = 60;
    if (duration < rule) {
      time =
      "00:00:${duration < 10 ? "0$duration" : "$duration"}";
    } else if (duration < rule * rule) {
      int minutes = duration ~/ rule;
      int seconds = duration - minutes * rule;
      String m = minutes < 10 ? "0$minutes" : "$minutes";
      String s = seconds < 10 ? "0$seconds" : "$seconds";
      time = "00:$m:$s";
    } else {
      int hours = duration ~/ (rule * rule);
      int residue = duration - hours * rule * rule;
      int minutes = residue ~/ rule;
      int seconds = residue - minutes * rule;
      String h = hours < 10 ? "0$hours" : "$hours";
      String m = minutes < 10 ? "0$minutes" : "$minutes";
      String s = seconds < 10 ? "0$seconds" : "$seconds";
      time = "$h:$m:$s";
    }

    return model.assetEntity.type == AssetType.video
        ? Positioned(
      left: 0,
      right: 0,
      bottom: 0,
      height: 15,
      child: Container(
        padding: const EdgeInsets.only(left: 5),
        alignment: Alignment.centerLeft,
        decoration: BoxDecoration(
          gradient: LinearGradient(
              begin: Alignment.topCenter,
              end: Alignment.bottomCenter,
              colors: [
                Colors.transparent,
                Colors.grey
              ]),
        ),
        child: Text(
          time,
          style: TextStyle(
            fontSize: KDimens.font_sp10,
            fontWeight: FontWeight.w400,
            color: Colours.colorFFFFFF,
          ),
        ),
      ),
    )
        : const SizedBox();
  }
}
